<template>
  <!--菜单权限管理-->
  <el-row style="height:100%">
    <page @buttons="configPermissions">
      <pageheader :event="'offonPopUp'" :isShow="buttonPermissions.isAdd || buttonPermissions.isAddAdmin">
        菜单权限管理
      </pageheader>
      <div class="page-content">
        <el-card class="box-card">
          <el-row>
            <el-col :span="16">
              <div style="height: 45px;">
                <Cascader
                  :value="company_id_arr"
                  :options.sync="options"
                  :width="'300px'"
                  :changeEvent="'roleDataChange'">
                  所属企业：</Cascader>
              </div>
            </el-col>
          </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="角色名称" prop="role_name" align="left" sortable></el-table-column>
            <el-table-column label="所属集团" prop="company_name" align="center" sortable></el-table-column>
            <el-table-column label="角色描述" prop="role_desc" align="center" sortable></el-table-column>
            <el-table-column label="是否是企业管理员" prop="is_company_admin_str" align="center"></el-table-column>
            <el-table-column v-if="buttonPermissions.isWatch || buttonPermissions.isDel || buttonPermissions.isModifyWatch" label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button v-if="(scope.row.is_company_admin == 1 && buttonPermissions.isModifyWatch) || (scope.row.is_company_admin == 0 && buttonPermissions.isWatch)"
                  @click="roleData(scope.row)" size="small">详情</el-button>
                <el-button v-if="buttonPermissions.isDel && scope.row.is_company_admin != 1"
                  @click="roleDel(scope.row)" type="danger" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager, next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
        <el-dialog v-dialogDrag :title="pageTitle" :visible.sync="isShow" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="800px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="角色名称" prop="role_name">
              <el-input v-model="ruleForm.role_name" size="small" style="width:450px" ></el-input>
            </el-form-item>
            <el-form-item label="所属企业" prop="company_id_arr">
              <Cascader :value.sync="ruleForm.company_id_arr"
                        :options="options"
                        :changeEvent="'companyChange'"
                        :width="'450px'"
                        :disabled="isDisabled"
                        :isClearable="false"></Cascader>
            </el-form-item>
            <el-form-item label="角色描述" prop="role_desc">
              <el-input v-model="ruleForm.role_desc" type="textarea" size="small" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="菜单选择">
              <el-tree
                :data="treeData"
                :default-checked-keys="ruleForm.menu_id_list"
                :default-expanded-keys="ruleForm.menu_id_list"
                node-key="id"
                @check="clickCheck"
                ref="Tree"
                :check-strictly="true"
                :props="defaultProps"
                show-checkbox>
              </el-tree>
              <el-button v-if="isRoot"
                type="primary" size="small" @click="pushPower">快速配置运维工程师</el-button>
            </el-form-item>
            <el-form-item label="是否是管理员" v-if="!isDisabled && buttonPermissions.isAddAdmin" prop="isAdmin">
              <el-radio-group v-model="ruleForm.isAdmin" @change="isAdminChange" size="small">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button v-if="(!isDisabled && (buttonPermissions.isAdd || buttonPermissions.isAddAdmin)) ||
                              (isDisabled && isAdmin && buttonPermissions.isModifyAdmin) ||
                               (isDisabled && !isAdmin && buttonPermissions.isModify)"
              type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
.page-content {
  padding: 15px;
  .fr {
    float: right;
  }
  .el-table {
    margin-bottom: 10px;
  }
  .paging {
    margin: 15px;
    height: 28px;
  }
}
</style>
<script>
import page from "@/components/page/page";
import pageheader from "@/components/page/pageheader";
import Cascader from "@/components/sys/assembly/elcascader";
import reportGlobal from "@/components/global/reportGlobal";//公共配置

const menu_id_list = reportGlobal.menu_id_list
export default {
  data() {
    return {
      pageTitle: "菜单权限管理",
      options:[],//级联控件 所属企业
      isShow: false,//是否显示普通模态框
      isShow_admin: false,//是否显示管理员模态框
      isDisabled:false,//是否是修改状态
      role_id:'',//修改状态时，存储角色id
      isAdmin:false,//修改角色身份是否为管理员
      company_id:'',//选择企业ID
      company_id_arr:[],//选择企业ID arr
      dataTable:[],//表格数据
      pagination:{
        total:0,//总条目数
        currentPage:1,//当前页数
        pageSize:10,//每页显示条目个数
        pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
      },//表格分页参数
      ruleForm: {
        role_name: '',//角色名称
        company_id_arr: [],//所属企业arr
        company_id: '',//所属企业str
        menu_id_list: [],//菜单id列表
        role_desc: '',//角色描述
        isAdmin:0,//是否是管理员
      },//普通角色模态框form表单
      rules: {
        role_name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        company_id_arr: [{ required: true, message: "请选择所属企业",trigger:'change'}],
      },//普通角色form表单验证
      treeData:[],//菜单选择树形结构
      defaultProps:{
        label: 'menu_name',
      },//树形控件配置选项
      isRoot:false,//是否是管理员
      buttonPermissions:{
        isAdd:false,
        isAddAdmin:false,
        isDel:false,
        isModify:false,
        isModifyAdmin:false,
        isWatch:false,
        isModifyWatch:false,
      }
    }
  },
  components: {
    page,
    pageheader,
    Cascader//级联选择器组件
  },
  created() {
    if(sessionStorage.buttonPermissions){
      this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
    }
    if(localStorage.isRoot){
      this.isRoot = localStorage.isRoot == 1 ? true :false
    }
  },
  mounted() {
    //初始化页面
    this.getTree()
    //新增按钮点击事件
    this.$Bus.$on("offonPopUp", () => {
      this.isShow = true;
      this.isDisabled = false;
      // this.getAuthTree()
    });
    //所属企业change事件
    this.$Bus.$on("roleDataChange", data => {
      this.company_id = data.slice(-1)[0];
      this.$Bus.$emit('Loading',true)
      this.roleList(this.company_id)
    });
    //添加和修改中选择所属企业change事件
    this.$Bus.$on('companyChange',data =>{
      this.ruleForm.company_id_arr = data
      this.ruleForm.company_id = data.slice(-1)[0]
      this.$nextTick(()=>{
        this.$refs.ruleForm.validateField('company_id_arr');//触发form表单中校验所属企业是否选择
      })
      //如果选择了是管理时则不调用菜单权限
      if(!this.ruleForm.isAdmin && this.ruleForm.company_id){
        this.$Bus.$emit('Loading',true)
        this.getAuthTree(this.ruleForm.company_id);//选择完企业后获取企业下菜单列表权限
      }
    })
  },
  beforeDestroy(){
    this.$Bus.$off('offonPopUp')
    this.$Bus.$off('roleDataChange')
    this.$Bus.$off('companyChange')
  },
  methods: {
    //表格序号显示方法
    indexMethod(index){
      return index + ((this.pagination.currentPage - 1) * this.pagination.pageSize) + 1
    },
    //是否是管理员change事件
    isAdminChange(val){
      if(val){
        //当选择是管理员时调用不传参数，直接获取该用户当前所有菜单权限
        this.getAuthTree()
      }else{
        //当选择是非管理员时，根据选择企业id来获取菜单权限
        if(this.ruleForm.company_id){
          this.$Bus.$emit('Loading',true)
          this.getAuthTree(this.ruleForm.company_id)
        }else{
          this.treeData = [];
        }
      }
    },
    //配置按钮权限，根据权限不同调整表头渲染参数
    configPermissions(val){
      let buttonPermissions = val
      let menuButtonPermissions = [];//按钮权限数组
      buttonPermissions.forEach(e =>{
        for(let key in e){
          if(key == 'menu_code'){
            menuButtonPermissions.push(e[key])
          }
        }
      });
      this.buttonPermissions.isAdd = menuButtonPermissions.includes('roleControlAdd') ? true : false; //是否有新增权限
      this.buttonPermissions.isAddAdmin = menuButtonPermissions.includes('roleControlAddAdmin') ? true : false; //是否有新增管理员权限
      this.buttonPermissions.isDel = menuButtonPermissions.includes('roleControlDelete') ? true : false; //是否有删除权限
      this.buttonPermissions.isModify = menuButtonPermissions.includes('roleControlModify') ? true : false; //是否有修改权限
      this.buttonPermissions.isModifyAdmin = menuButtonPermissions.includes('roleControlModifyAdmin') ? true : false; //是否有管理员修改权限
      this.buttonPermissions.isWatch = menuButtonPermissions.includes('roleControlWatch') ? true : false; //是否有查看权限
      this.buttonPermissions.isModifyWatch = menuButtonPermissions.includes('roleControlModifyWatch') ? true : false; //是否有查看管理员权限
    },
    //获取企业tree
    getTree(){
      let url = '/sys/report_assist_new/company_tree';
      this.$api.get(url)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          recursion(data.data);
          function recursion(val) {
            if(val.length){
              for(let i in val){
                val[i].value = val[i].id;
                val[i].label = val[i].company_name;
                val[i].parent_id_str = val[i].parent_name_list.join('/');
                if(val[i].children && val[i].children.length){
                  recursion(val[i].children)
                }else{
                  delete val[i].children
                }
              }
            }
          }
          this.options = data.data
          this.company_id_arr.push(data.data[0].id)
          this.company_id = data.data[0].id
          this.roleList(data.data[0].id)
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //获取角色列表
    roleList(company_id='',page='1',page_size='10'){
      this.dataTable = []
      let url = '/sys/role/list?company_id='+ company_id + '&page=' + page + '&page_size=' + page_size
      this.$api.get(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data.data){
          let _data = data.data;
          if( _data.dataList){
            _data.dataList.forEach(x =>{
              return x.is_company_admin_str = x.is_company_admin ? '是' : '否'
            })
            this.dataTable = _data.dataList
          }
          this.pagination.total = _data.dataCount;
          this.pagination.currentPage = _data.pageCode;
          this.pagination.pageSize = _data.pageSize;
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //关闭模态框
    closeDialog(formName){
      this.treeData = null
      this.ruleForm.menu_id_list = [];
      this.$refs[formName].resetFields();
      this.$Bus.$emit('Loading',false)
    },
    //获取用户菜单列表
    getAuthTree(id = ''){
      let url = '/sys/menu/auth_tree?company_id=' + id
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          if(this.isRoot) {
            for (let i in data.data) {
              if (data.data[i].menu_url == 'realTimeChain')data.data[i].menu_name = '实时数据驾驶舱(连锁店)'
              if (data.data[i].menu_url == 'realTimeMall')data.data[i].menu_name = '实时数据驾驶舱(购物中心)'
            }
          }
          this.treeData = data.data
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.treeData = []
        this.$Bus.$emit('Loading',false)
      })
    },
    //tree结构的复选框实现子集选中时选中所有父级，子集取消时取消所有子级
    clickCheck(data,checkedKeys){
      let parentArr = [];
      //找到子集并选中他们
      let openChildrens = arr =>{
        parentArr = data.node_location.split('-')
        parentArr.forEach(x=>{
          this.$refs.Tree.setChecked(x,true);
        })
        for(let i in arr.children){
          this.$refs.Tree.setChecked(arr.children[i].id,true);
          if(arr.children[i].children != 0){
            openChildrens(arr.children[i])
          }
        }
      };
      //找到子集并取消他们
      let clearChildrens = arr =>{
        for(let i in arr.children){
          this.$refs.Tree.setChecked(arr.children[i].id,false);
          if(arr.children[i].children != 0){
            clearChildrens(arr.children[i])
          }
        }
      };

      if(checkedKeys.checkedKeys.includes(data.id)){
        openChildrens(data);
      }else{
        //当点击tree为取消状态，则通过clearChildrens方法，找到子集并取消他们
        clearChildrens(data)
      }
    },
    //点击修改事件；
    roleData(data){
      this.isDisabled = true
      this.isShow = true;
      this.role_id = data.id
      this.isAdmin = data.is_company_admin ? true : false

      this.$Bus.$emit('Loading',true)
      //如果为查询管理员时，调用菜单权限接口不传递企业id，直接获取该用户的最大权限
      if(this.isAdmin){
        this.getAuthTree()
      }else{
        this.getAuthTree(data.company_id)
      }
      this.getRole(data.id);//调用角色信息获取
      this.getCompany(data.company_id);//调用企业信息中的node_location
    },
    //获取角色信息
    getRole(id){
      let url = '/sys/role/get?role_id='+ id
      this.$api.get(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          let _data = data.data;
          this.ruleForm.role_name = _data.role_name;
          this.ruleForm.role_desc = _data.role_desc;
          this.ruleForm.company_id = _data.company_id;
          this.ruleForm.menu_id_list = _data.menu_id_list;
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //获取企业信息中的node_location
    getCompany(id=''){
      let url = '/sys/company/get?id='+ id
      this.$api.get(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          let node_location = data.data.node_location.split('-')
          node_location.splice(-1,1)
          this.ruleForm.company_id_arr = node_location
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },

    //删除按钮点击事件
    roleDel(data){
      this.$confirm("是否删除‘"+ data.role_name +"’？", "提示",{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center:true
      })
      .then(() => {
        this.$Bus.$emit('Loading',true)
        this.delData(data.id);
      })
      .catch(() => {});
    },
    //删除接口
    delData(id) {
      let url = "/sys/role/del";
      let data = {
        role_id:id
      }
      this.$api.delete(url,data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.roleList(this.company_id,this.pagination.currentPage,this.pagination.pageSize)
          this.$message({
            message: "删除成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
    },
    //每页显示条目个数change事件
    sizeChange(val){
      this.$Bus.$emit('Loading',true)
      this.roleList(this.company_id,this.pagination.currentPage,val)
    },
    //分页change事件
    currentChange(val){
      this.$Bus.$emit('Loading',true)
      this.roleList(this.company_id,val,this.pagination.pageSize)
    },
    //模态框保存按钮
    confirmDialog(formName){
      let data = {};
      let model = null
      let url = ''
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$Bus.$emit('Loading',true)
          model = this.$refs[formName].model;
          model.company_id = model.company_id_arr.length !== 0 ? model.company_id_arr.slice(-1)[0] : '';
          //判断模态框开启状态 true：修改：false：新增
          if(this.isDisabled){
            //判断是否为修改管理员角色
            if(this.isAdmin){
              url = '/sys/role/update_admin?role_id=' + this.role_id
            }else{
              url = '/sys/role/update?role_id=' + this.role_id
            }
            data.menu_id_list = this.$refs.Tree.getCheckedKeys()
            data.role_desc = model.role_desc
            data.role_name = model.role_name
            this.roleUpdata(url,data)
          }else{
            if(this.buttonPermissions.isAdd && this.ruleForm.isAdmin){
              url = '/sys/role/add_admin'
            }else{
              url = '/sys/role/add'
            }
            data.menu_id_list = this.$refs.Tree.getCheckedKeys()
            data.company_id = model.company_id
            data.role_desc = model.role_desc
            data.role_name = model.role_name
            this.roleAdd(url,data)
          }
        } else {
          console.log("error submit!!");
          return;
        }
      });
    },

    //新增保存
    roleAdd(url,data){
      this.$api.post(url,data)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.isShow = false;
          this.isShow_admin = false;
          this.roleList(this.company_id,this.pagination.currentPage,this.pagination.pageSize)
          this.$message({
            message: "新增成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
    },
    //修改角色保存
    roleUpdata(url,data){
      this.$api.put(url,data)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.isShow = false;
          this.isShow_admin = false;
          this.roleList(this.company_id,this.pagination.currentPage,this.pagination.pageSize)
          this.$message({
            message: "修改成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
    },
    //快速配置运维工程师
    pushPower(){
      this.$set(this.ruleForm,'menu_id_list',menu_id_list)
    }
  },
  watch: {}
};
</script>
